package cn.workreport.modules.organization.controller;

import cn.workreport.modules.common.annotations.UserLoginToken;
import cn.workreport.modules.common.controller.BaseController;
import cn.workreport.modules.common.enums.IsEnum;
import cn.workreport.modules.common.po.IdsPO;
import cn.workreport.modules.common.po.PagePO;
import cn.workreport.modules.common.vo.PageVO;
import cn.workreport.modules.organization.entity.Organization;
import cn.workreport.modules.organization.enums.OrgStatusEnum;
import cn.workreport.modules.organization.service.IOrganizationService;
import cn.workreport.modules.permission.enums.PermissionEnum;
import cn.workreport.modules.users.entity.UserExtends;
import cn.workreport.util.JsonResult;
import cn.workreport.util.PageQueryUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

/**
 * <p>
 * 机构 对应控制器
 * </p>
 *
 * @author yyf
 * @since 2022-03-24
 */
@Slf4j
@RestController
@UserLoginToken
@Api(tags = "机构模块")
public class OrganizationController extends BaseController {

    @Autowired
    private IOrganizationService organizationService;

    /**
     * 保存或修改机构
     *
     * @param entity 实体信息
     * @return 成功与否，成功返回实体信息，失败返回错误信息
     */
    @ApiOperation("修改或保存机构")
    @PostMapping("/organization/saveOrUpdate")
    public JsonResult<?> saveOrUpdate(Organization entity) {
        log.info("===> 进入 /organization/saveOrUpdate ===> params = " + entity);
        return organizationService.saveOrUpdateEntity(entity);
    }

    /**
     * 分页查询机构（需要权限）
     *
     * @param pagePO
     * @return 查询结果
     */
    @ApiOperation("分页查询机构（需要权限）")
    @UserLoginToken(permission = { PermissionEnum.ORG_PAGE })
    @PostMapping("/organization/listPage")
    public JsonResult<?> listPage(@RequestBody PagePO<Organization> pagePO){
        log.info("===> 进入 /organization/listPage ===> params = " + pagePO);
        IPage<Organization> page = new PageQueryUtil<Organization>().getPage(pagePO);
        LambdaQueryWrapper<Organization> wrapper = new LambdaQueryWrapper<>();
        Organization condition = pagePO.getCondition();
        if (!ObjectUtils.isEmpty(condition)) {
            wrapper.like(!ObjectUtils.isEmpty(condition.getOrgName()), Organization::getOrgName, condition.getOrgName());
            wrapper.eq(!ObjectUtils.isEmpty(condition.getOrgStatus()), Organization::getOrgStatus, condition.getOrgStatus());
            wrapper.eq(!ObjectUtils.isEmpty(condition.getCanJoin()), Organization::getCanJoin, condition.getCanJoin());
            wrapper.eq(!ObjectUtils.isEmpty(condition.getOrgManagerId()), Organization::getOrgManagerId, condition.getOrgManagerId());
        }
        wrapper.orderByDesc(Organization::getCreatedTime);
        PageVO<Organization> result = organizationService.pageEntity(page, wrapper);
        if (!ObjectUtils.isEmpty(result)) {
            result.getList().forEach(entity -> organizationService.wrapEntity(entity));
        }
        return JsonResult.ok(result);
    }

    /**
     * 分页查询启用的机构（不需要权限）
     *
     * @param pagePO
     * @return 查询结果
     */
    @ApiOperation("分页查询启用的机构（不需要权限）")
    @PostMapping("/organization/listPageChoose")
    public JsonResult<?> listPageChoose(@RequestBody PagePO<Organization> pagePO){
        log.info("===> 进入 /organization/listPageChoose ===> params = " + pagePO);
        IPage<Organization> page = new PageQueryUtil<Organization>().getPage(pagePO);
        LambdaQueryWrapper<Organization> wrapper = new LambdaQueryWrapper<>();
        Organization condition = pagePO.getCondition();
        if (!ObjectUtils.isEmpty(condition)) {
            wrapper.like(!ObjectUtils.isEmpty(condition.getOrgName()), Organization::getOrgName, condition.getOrgName());
        }
//        wrapper.eq(Organization::getOrgStatus, OrgStatusEnum.ENABLE);
//        wrapper.eq(Organization::getCanJoin, IsEnum.YES);
        wrapper.orderByDesc(Organization::getCreatedTime);
        PageVO<Organization> result = organizationService.pageEntity(page, wrapper);
        if (!ObjectUtils.isEmpty(result)) {
            result.getList().forEach(entity -> organizationService.wrapEntity(entity));
        }
        return JsonResult.ok(result);
    }

    /**
     * 根据ID查询机构
     * 如果查询不到，new 一个返回，可以作为新建请求
     * @param id ID
     * @return 查询结果
     */
    @ApiOperation("根据ID查询机构")
    @GetMapping("/organization/getById")
    public JsonResult<?> getById(Integer id){
        log.info("===> 进入 /organization/getById ===> params: id" + id);
        if (ObjectUtils.isEmpty(id)) {
            return JsonResult.fail("参数 id 不能为空！");
        }
        Organization entity = organizationService.getByIdEntity(id);
        return JsonResult.ok(entity);
    }

    /**
    * 批量或单体删除机构数据
    *
    * @param idsPO ID集合
    * @return 成功与否
    */
    @ApiOperation("批量删除机构")
    @PostMapping("/organization/removeByIds")
    @UserLoginToken(permission = { PermissionEnum.ORG_DELETE })
    public JsonResult<?> removeByIds(IdsPO idsPO){
        log.info("===> 进入 /organization/removeByIds ===> params = " + idsPO);
        if (ObjectUtils.isEmpty(idsPO)) {
            return JsonResult.fail("ids 不能为空！");
        }
        return organizationService.removeByIdsEntity(idsPO.getIds());
    }

    /**
     * 机构预加载数据
     * @return
     */
     @ApiOperation("机构预加载数据")
     @GetMapping("/organization/preparedData")
     public JsonResult<?> preparedData() {
       return organizationService.preparedData();
     }

    /**
     * 设置机构停用/启用
     */
    @ApiOperation("设置机构停用/启用")
    @UserLoginToken(permission = { PermissionEnum.ORG_SET_STATUS })
    @PostMapping("/organization/setStatus")
    public JsonResult<?> setStatus(Integer orgId, OrgStatusEnum orgStatus){
        log.info("===> 进入 /organization/setStatus ===> params: orgId =" + orgId + ", orgStatus=" + orgStatus);
        if (ObjectUtils.isEmpty(orgId)) {
            return JsonResult.fail("缺少参数 orgId");
        }
        if (ObjectUtils.isEmpty(orgStatus)) {
            return JsonResult.fail("缺少参数 orgStatus");
        }
        return organizationService.setStatus(orgId, orgStatus);
    }

    /**
     * 设置机构是否可加入
     */
    @ApiOperation("设置机构是否可加入")
    @UserLoginToken(permission = { PermissionEnum.ORG_SET_CAN_JOIN })
    @PostMapping("/organization/setCanJoin")
    public JsonResult<?> setCanJoin(Integer orgId, IsEnum canJoin){
        log.info("===> 进入 /organization/setCanJoin ===> params: orgId =" + orgId + ", canJoin=" + canJoin);
        if (ObjectUtils.isEmpty(orgId)) {
            return JsonResult.fail("缺少参数 orgId");
        }
        if (ObjectUtils.isEmpty(canJoin)) {
            return JsonResult.fail("缺少参数 canJoin");
        }
        return organizationService.setCanJoin(orgId, canJoin);
    }

}
